<template>
  <div class="emergency">
    <!-- 地图 -->
    <div class="bm-view" id="container"></div>
    <!-- 召开中与待召开 -->
    <div v-if="zkStatus" class="zkStatus" @click="handleClickZK()">
      <i class="el-icon-phone"></i>
      <p>10:00:10</p>
    </div>
    <!-- 头部工具切换 -->
    <div class="gjGroup" style="z-index: 100;">
      <el-button-group>
        <el-button size="small" :type="item.value == gjCurrut ? 'primary' : ''" v-for="(item, index) in btnGroupgj"
          :key="index" @click="gjClick(item)">{{ item.name }}</el-button>
      </el-button-group>
      <el-button size="small" @click="draw()">开始绘制</el-button>
      <el-button size="small" @click="removedraw()">移除绘制</el-button>
      <el-button size="small" @click="addMarket()">添加market</el-button>
      <el-button size="small" @click="removeMarket()">清除market</el-button>
      <el-button size="small" @click="distanceOpen()">开启测距</el-button>
      <el-button size="small" @click="distanceClose()">关闭测距</el-button>
    </div>
    <!-- 通知弹窗 -->
    <informs ref="informRef" v-if="informIshow"></informs>
    <!-- 图层弹窗 -->
    <coverage ref="coverageRef" v-if="coverageIshow" @MapTypeClick="MapTypeClick" @MapTypeOtherClick="MapTypeOtherClick"
      @MapTypeListAllChange="MapTypeListAllChange"></coverage>
    <!-- 工具弹框 -->
    <tool ref="toolRef" v-if="toolIshow"></tool>
    <!-- 告警弹窗 -->
    <alarm ref="alarmRef" v-if="alarmIshow"></alarm>
  </div>
</template>

<script>
import informs from "@/views/emergency/gis/inform.vue";
import coverage from "@/views/emergency/gis/coverage.vue";
import tool from "@/views/emergency/gis/tool.vue";
import alarm from "@/views/emergency/gis/alarm.vue";
import '@/utils/GeoUtils.js' //计算几何方法
export default {
  components: {
    informs,
    coverage,
    tool,
    alarm,
  },
  data() {
    return {
      btnGroupgj: [
        { name: "通知", value: 1 },
        { name: "图层", value: 2 },
        { name: "工具", value: 3 },
        { name: "告警", value: 4 },
      ], //工具组
      gjCurrut: 1, //工具选中值
      // 百度地图参数
      BMcenter: { lng: 116.404, lat: 39.915 },
      BMzoom: 15,
      bmap: null, //地图实例
      BMap: null, //地图对象
      // 弹窗
      informIshow: false,
      toolIshow: false,
      coverageIshow: false,
      alarmIshow: false,
      // 地图属性
      MapType: null,//地图类型
      styleOptions:{
        strokeColor: '#5E87DB',   // 边线颜色
        fillColor: '#5E87DB',     // 填充颜色。当参数为空时，圆形没有填充颜色
        strokeWeight: 2,          // 边线宽度，以像素为单位
        strokeOpacity: 1,         // 边线透明度，取值范围0-1
        fillOpacity: 0.2          // 填充透明度，取值范围0-1
      },
      labelOptions: {
        borderRadius: '2px',
        background: '#FFFBCC',
        border: '1px solid #E1E1E1',
        color: '#703A04',
        fontSize: '12px',
        letterSpacing: '0',
        padding: '5px'
      },
      map:null,//地图实例
      distanceMap:null,//地图测距实例
      drawingManager:null,//地图绘图实例
      zkStatus: true//true说明视频会议有进行中的
    };
  },
  mounted() { 
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    // 初始化地图，设置中心点坐标和地图级别
    init() {
      this.map = new BMapGL.Map("container");          // 创建地图实例 
      var point = new BMapGL.Point(116.404, 39.915);  // 创建点坐标 
      this.map.centerAndZoom(point, 15);
      this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放 
      this.distanceMap = new BMapGL.DistanceTool(this.map);
    },
    draw() {
      // 实例化鼠标绘制工具
      this.drawingManager = new BMapGLLib.DrawingManager(this.map, {
        // isOpen: true,        // 是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingMode: BMAP_DRAWING_POLYGON,//绘制模式 多边形
        drawingToolOptions: {
          anchor: BMAP_ANCHOR_TOP_LEFT, //位置
          offset: new BMap.Size(30, 5), //偏离值
          // drawingModes: drawing,//BMAP_DRAWING_RECTANGLE-矩形 BMAP_DRAWING_MARKER 画点 BMAP_DRAWING_CIRCLE 画圆 BMAP_DRAWING_POLYLINE 画线
          drawingModes: [
            BMAP_DRAWING_MARKER,
            BMAP_DRAWING_POLYGON,
            //   BMAP_DRAWING_POLYLINE,
            //   BMAP_DRAWING_RECTANGLE,
            //   BMAP_DRAWING_CIRCLE
          ], //画线类型
          scale: 0.8
        },
        enableCalculate: true, // 绘制是否进行测距测面
        enableSorption: true,   // 是否开启边界吸附功能
        sorptiondistance: 20,   // 边界吸附距离
        enableGpc: true,        // 是否开启延边裁剪功能
        // enableLimit: true,      // 是否开启超限提示
        // limitOptions: {
        //   area: 50000000000000,     // 面积超限值
        //   distance: 30000000000000     // 距离超限值
        // },
        circleOptions: this.styleOptions,     // 圆的样式
        polylineOptions: this.styleOptions,   // 线的样式
        polygonOptions: this.styleOptions,    // 多边形的样式
        rectangleOptions: this.styleOptions,  // 矩形的样式
        labelOptions: this.labelOptions,      // label样式
      });
      this.drawingManager.open();
      // 鼠标绘制事件总监听(无论哪种绘制，绘制完成都会调用)
      this.drawingManager.addEventListener('overlaycomplete', this.overlaycomplete.bind(this))
    },
    //鼠标绘制完成回调方法获取各个点的经纬度
    overlaycomplete(e) {
      // e.overlay; // 对应的绘制模式返回对应的覆盖物
      var overlays = [];
      // 自定义绘图类型方便后面想删除哪个图形
      // e.overlay.type = 'draw'
      // overlays.push(e.overlay);
      // console.log('overlays', e)
      if (e.drawingMode == 'marker') {
        let lng = e.overlay.latLng.lng
        let lat = e.overlay.latLng.lat
        // console.log('坐标点：',JSON.stringify(e.overlay.latLng))
      } else {
        // var path = e.overlay.getPath();//Array<Point> 返回多边型的点数组
        // 做个标识
        e.overlay.id = 'draw-' + new Date().getTime()
        overlays.push(e.overlay);
      }
    },
    //清除地图上所有覆盖物
    clearAllOverlay() {
      let overlays = this.map.getOverlays()
      console.log('获取所有绘制图', overlays)
      this.map.clearOverlays()
    },
    // 移除绘制图
    // removedraw() {
    //   let overlays = this.map.getOverlays()
    //   console.log('获取所有绘制图', overlays)
    //   for (let item in overlays) {
    //     this.map.removeOverlay(overlays[item])
    //   }
    // },
    // 移除绘制图
    removedraw(){
      let overlays = this.map.getOverlays()
      console.log('获取所有绘制图', overlays)
      for(let item in overlays){
        if (overlays[item].type == 'draw'){
          this.map.removeOverlay(overlays[item])
        }
      }
      this.drawingManager.close();
      this.drawingManager._isOpen = false
      this.clearAllOverlay()
    },
    //添加market
    addMarket(){
      let lng = Number(((Math.random()/100) + 116.382).toFixed(6))
      let lat = Number(((Math.random()/100) + 39.911).toFixed(6))
      var point = new BMapGL.Point(lng, lat);
      var marker = new BMapGL.Marker(point); 
      marker.id = 'marker-'+Math.random()     // 创建标注   
      this.map.addOverlay(marker);                     // 将标注添加到地图中
    },
    // 清除marker
    removeMarket(){
      let overlays = this.map.getOverlays()
      console.log('获取所有绘制图', overlays)
      for (let item in overlays) {
        if (overlays[item].id && overlays[item].id.indexOf('marker')>-1) {
          this.map.removeOverlay(overlays[overlays.length-1])
        }
      }
    },
    // 开启测距
    distanceOpen(){
      this.distanceMap.open();  //开启鼠标测距
    },
    // 关闭测距
    distanceClose(){
      this.distanceMap.close();  //关闭鼠标测距
    },
    // 图层弹框-设备信息-icon-点击事件
    MapTypeOtherClick(val) {
      console.log("MapTypeOtherClick", val, val.checked);
      // 视频监控,应该是它的标识，目前就取的ID
      if (val.id && val.checked) {
        console.log(111)
        let points = val.points //先获取所有视频监控的点
        // console.log('视频监控的点',points)
        if (points && points.length > 0) {

        } else {
          alert('该位置没有点集合')
          return false
        }
        let overlays = this.map.getOverlays() //获取所有图形
        // console.log('获取所有绘制图', overlays)
        // 先筛选出带 draw标识 多边形图形,一般是一个或者你点中的那个图形对象
        let drawoverlays = null
        if (overlays.length <= 0) {
          alert('咱没有绘制图形')
          return false
        }
        overlays.map((item) => {
          if (item.id && item.id.indexOf('draw') > -1) {
            drawoverlays = item
          }
        })
        // console.log('drawoverlays-选中多边形实例',drawoverlays)
        // 多边形区域的点的集合
        let Polygons = []
        var path = drawoverlays.getPath();//对象坐标点集合
        for (var i = 0; i < path.length; i++) {
          // console.log("lng:" + path[i].lng + "\n lat;" + path[i].lat);
          Polygons.push(new BMap.Point(path[i].lng, path[i].lat))
        }
        // console.log('多边形区域点集合',path)
        // console.log('多边形区域点集合-Polygons',Polygons)
        // 获取多边形对象
        var polygon = new BMap.Polygon(Polygons, { strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.5 });
        // 在区域内的point
        let areapoint = []
        // 先筛选出在图形内的point
        points.map((item) => {
          // 监听点是否在多边形区域内
          var result = BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(item.lng, item.lat), polygon);
          if (result == true) {
            areapoint.push(new BMap.Point(item.lng, item.lat))
          }
        })
        // console.log('在区域内的点集合',areapoint,map1)
        // 创建自定义覆盖物DOM
        const createDOM = (iconfont) => {
          const div1 = document.createElement('div');
          const i = document.createElement('i');
          div1.classList = 'mapicon'
          i.classList = val.icon
          div1.appendChild(i)
          return div1;
        }
        // 如果在区域内有集合的点存在
        if (areapoint.length > 0) {
          areapoint.map((item) => {
            // 创建标注对象并添加到地图  
            const customOverlay = new BMapGL.CustomOverlay(createDOM, {
              point: item,
              opacity: 0.5,
              // map: map,
              offsetY: -10,
              // properties: {
              //   title: 'this is a title',
              //   size: '100'
              // }
            });
            customOverlay.CustomOverlayId = val.id
            this.map.addOverlay(customOverlay);
          })
        }

      } else {
        let overlays = this.map.getOverlays()
        console.log('获取所有绘制图222', overlays)
        for (let item in overlays) {
          if (overlays[item].CustomOverlayId == val.id) {
            this.map.removeOverlay(overlays[item])
          }
        }
      }
    },
    // 图层弹窗-是否全在地图上显示
    MapTypeListAllChange(val) {
      console.log("MapTypeListAllChecked", val);
      // 同理 MapTypeOtherClick 这个方法
      // 先清除再添加
      let overlays = this.map.getOverlays()
      console.log('获取所有绘制图', overlays)
      for (let item in overlays) {
        if (overlays[item].CustomOverlayId) {
          this.map.removeOverlay(overlays[item])
        }
      }
      // 1,多维拉成一维
      let arr = []
      val.map((item, index) => {
        if (item.list && item.list.length > 0) {
          item.list.map((itv) => {
            if (itv.points && itv.points.length > 0 && itv.checked) {
              arr.push(itv)
            }
          })
        }
      })
      console.log('arr', arr)
      // 2.遍历有坐标点的数据
      if (arr.length <= 0) {
        alert('暂无点集合')
        return false
      }
      arr.map((item) => {
        this.MapTypeOtherClick(item)
      })
    },
    // 是否回到视频调度页面
    handleClickZK() {
      this.$router.push({ path: "/meet/video" });
    },
    
    // 百度地图初始化
    readHandler({ BMap, map }) {
      console.log(BMap, map);
      // 经纬度暂时随便写的
      this.BMcenter.lng = 116.404;
      this.BMcenter.lat = 39.915;
      this.BMzoom = 15;
      this.bmap = map;
      this.BMap = BMap;
    },
    /**工具选中事件 */
    gjClick(item) {
      console.log(item);
      this.gjCurrut = item.value;
      if (this.gjCurrut == 2) {
        this.coverageIshow = true;

        this.$nextTick(() => {
          this.$refs.coverageRef.init();
        });
        this.toolIshow = false;
      } else if (this.gjCurrut == 1) {
        this.informIshow = true;
        this.$nextTick(() => {
          this.$refs.informRef.init();
        });
        this.toolIshow = false;
      } else if (this.gjCurrut == 4) {
        this.alarmIshow = true;
        this.$nextTick(() => {
          this.$refs.alarmRef.init();
        });
        this.toolIshow = false;
      } else if (this.gjCurrut == 3) {
        this.toolIshow = true;

        this.$nextTick(() => {
          this.$refs.toolRef.init();
        });
      }
    },
    // 地图类型点击事件
    MapTypeClick(val) {
      console.log('地图类型点击事件-子组件传过来的值', val)
      this.MapType = val.value
      this.map.setMapType(val.value)
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/emergency.scss";
</style>
<style lang="scss" scoped>
@import "../../assets/emergency_gis.scss";
</style>
<style lang="scss">
  .mapicon {
    width: 36px;
    height: 36px;
    border: 1px solid #ddd;
    border-radius: 50%;
    margin-bottom: 5px;
    text-align: center;
    line-height: 36px;
    background-color: #fff;

    i {
      font-size: 20px;
    }
  }
</style>